package com.project.shiro;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;

import javax.annotation.Resource;

public class CustomRealm extends AuthorizingRealm {
    @Resource
    private IUserService userService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//        //获取当前登录的用户
//        UserBean userInfoBean = (UserBean) principalCollection.getPrimaryPrincipal();
//        //通过SimpleAuthenticationInfo做授权
//        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        // 得到当前用户包含的所有角色
//        List<RoleBean> roleInfoBeans = userInfoBean.getRoleBeans();
//        List<JurisdictionBean> functionInfoBeans = jurisdictionService.selectByRoleId(roleInfoBeans);
//        for (RoleBean role : roleInfoBeans) {
//            //添加角色
//            simpleAuthorizationInfo.addRole(role.getName());
//        }
//        for (JurisdictionBean function : functionInfoBeans) {
//            //添加权限
//            simpleAuthorizationInfo.addStringPermission(function.getName());
//        }
//        return simpleAuthorizationInfo;
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 身份认证的操作
        //1.获取用户输入的账号
        String username = (String) authenticationToken.getPrincipal();
        //2.通过username从数据库中查找到user实体
        UserBean  userBean = userService.selectByUserName(username);
        if (userBean == null) {
            return null;

        }
        //3.通过SimpleAuthenticationInfo做身份处理
        SimpleAuthenticationInfo simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(userBean, userBean.getPwd(), getName());
        //4.返回身份处理对象
        return simpleAuthenticationInfo;

    }
}
